<?php

namespace App\Http\Controllers;

use App\Http\Models\Album;
use App\Http\Models\Photo;
use App\Http\Models\UserAlbum;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;

class AlbumController extends Controller
{
    /*
     * 获取当前用户所有的相册
     */
    public function index()
    {
        $user_id = request('user_id');
        if(!$user_id){
            return api_return(0,'没有该用户相册');
        }
        //通过用户找到该拥有的所有album_id
        $userAlbums = UserAlbum::where('user_id',$user_id)->get();
        $albums = [];

        //通过所有的album_id,找到相册数据
        foreach ($userAlbums as $item){
            //获取该用户下的所有相册
            $album = Album::find($item['album_id']);
            $album['is_create'] = $item->is_create;
            $album['thumb'] = asset($item->thumb);
            $albums[] = $album;
        }

        return api_return(1,'成功',$albums);
    }

    /*
     * 获取相册详情
     */
    public function show($album_id){

        $album = Album::find($album_id);
        $user_id = request('user_id');

        $condition = ['album_id'=>$album['id'],'user_id'=>$user_id];

        $is_create = UserAlbum::where($condition)->first()['is_create'];

        $album['is_create'] = $is_create;
        $album['thumb'] = asset($album['thumb']);
//        foreach ($album->)
//        return ['album_id'=>$album_id,'album_users'=>$album->getUsers];
        //找到该相册下的所有用户

        return $album;

    }

    /*
     * 创建相册
     */
    public function store()
    {
        $name = request('name');
        $user_id = request('user_id');
        $time = date('Y-m-d',time());
        $res = Album::create(['name'=>$name,'create_time'=>$time]);
        if($res)
        {
            $data = [
                'user_id' => $user_id,
                'album_id' => $res['id'],
                'is_create' => 1
            ];
            $res = UserAlbum::create($data);
            if(!$res){
                return api_return(0,'关联相册失败');
            }
        }
        return api_return(1,'相册创建成功');
    }

    /*
     * 修改相册名称
     */
    public function update(Request $request, $id){
        $name = $request->name;
        $is_top = $request->is_top;

        $res = '';
        if($name){
            $res = Album::where('id',$id)->update(['name'=>$name]);
        }else if($is_top){
            $res = Album::where('id',$id)->update(['is_top'=>$is_top]);
        }

        if(!$res){
            return api_return(0,'该相册不存在',[]);
        }

        return api_return(1,'修改成功',$res);
    }
    /*
     * 修改封面
     */
    public function updateThumb(Request $request){
        if(!$file = $request->file('file')){
            $file = $request->file('file');         //前端框架默认key=file
        }
        $fileTypes = array('jpg', 'jpeg', 'png', 'gif');      // 允许上传类型
        $max_size = 2048000;
        // 本地上传
        if (empty($file)) {
            return api_return(false, '上传失败，文件为空！');
        }
        if (in_array($file->extension(), $fileTypes)) {
            if ($file->getClientSize() <= $max_size) {
                // 图片处理
                $fileName = time() . uniqid() . str_random(4) . '.' . $file->extension();
                $subDir = 'thumb';

                if(!is_dir(public_path("img/$subDir"))){
                    Storage::disk('public')->makeDirectory("img/$subDir");
                }

                $path = '/img' . "/$subDir/" . $fileName;
                $realPath = $file->getRealPath();

                Storage::disk('public')->put($path,file_get_contents($realPath));

                //保存文件路径到数据库
                $album_id = request('album_id');
                Album::where('id',$album_id)->update(['thumb'=>$path]);
                return api_return(true, '图片上传成功！', ['asset_url' => asset($path), 'images' => $path]);
            } else {
                return api_return(false, '上传失败，文件大小超过' . $max_size . '字节');
            }
        } else {
            return api_return(false, '只允许上传' . json_encode($fileTypes) . '格式文件');
        }

    }

    /*
     * 删除相册
     */
    public function destroy($id){
        $is_create = request('is_create');
        $user_id = request('user_id');
//        return [
//            'user_id'=>$user_id,
//            'is_create'=>$is_create
//        ];
        //相册创建者可以删除相册
        if($is_create){
            $res = Album::destroy($id);
//            return $res;
            if(!$res){
                return api_return(0,'删除相册失败',[]);
            }
            //删除相册下所有照片
            //先查看是否有照片
            $res = Photo::where('album_id',$id)->first();
            if($res){
                $res = Photo::where('album_id',$id)->delete();
                if(!$res){
                    return api_return(0,'照片删除失败',[]);
                }
            }
            //删除相册用户关联
            $res = UserAlbum::where('album_id',$id)->delete();
            if(!$res){
                return api_return(0,'删除关联用户失败',[]);
            }
            return api_return(1,'删除成功',[]);
        }else{
            //只删除改用户的照片与关联
            //先查看该用户是否有相片
            $has_photo = Photo::where('user_id',$user_id)->first();
            if($has_photo){
                //删除照片
                $del_num = Photo::where('user_id',$user_id)->delete();
                //修改相册照片数量
                Album::where('id',$id)->decrement('photo_num',$del_num);
                if(!$del_num){
                    return api_return(0,'删除用户照片失败');
                }
            }

            //删除关联记录
            $condition = [
                'user_id' => $user_id,
                'album_id' => $id
            ];
            $res = UserAlbum::where($condition)->delete();
            if(!$res){
                return api_return(0,'删除关联失败',[]);
            }

            return api_return(1,'成功退出该相册',[]);
        }
    }

}
